package org.jeecg.modules.rental.mq.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.base.BaseMap;
import org.jeecg.modules.rental.entity.RentalOrder;
import org.jeecg.modules.rental.service.IRentalAccountCouponService;
import org.jeecg.modules.rental.service.IRentalOrderService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author by sean
 * @desc: 处理支付租赁电单车订单
 * @since 2024-10-14 星期一 14:41:28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RentalEBIkeOrderService {

    private final IRentalOrderService rentalOrderService;
    private final IRentalAccountCouponService accountCouponService;

    @Transactional
    public void processOrder(Long orderId, BaseMap map) {
        log.debug("业务处理开始：{}", orderId);

        RentalOrder rentalOrder = rentalOrderService.getById(orderId);
        if (rentalOrder == null) {
            log.error("没有找到租车订单: {}", orderId);
            return;
        }

        // 幂等性校验：检查订单状态
        if (rentalOrder.getOrderStatus() != 1) {
            log.warn("订单 {} 状态已更新为 {}，跳过处理", orderId, rentalOrder.getOrderStatus());
            return;
        }

        accountCouponService.handleCoupon(rentalOrder);
        LocalDateTime now = LocalDateTime.now();
        rentalOrder.setOrderStatus(2);
        rentalOrder.setPayTime(now);
        rentalOrderService.updateById(rentalOrder);

        switch (rentalOrder.getOrderType()) {
            case 1:
                rentalOrderService.handleRentalOrder(rentalOrder, now);
                break;
            case 2:
                rentalOrderService.handleRenewalOrder(rentalOrder);
                break;
            case 3:
                rentalOrderService.handleOvertimeOrder(rentalOrder);
                break;
            case 4:
                rentalOrderService.handleReservationOrder(rentalOrder, now);
                break;
            default:
                log.warn("未知订单类型: {}", rentalOrder.getOrderType());
        }
        log.debug("业务处理完成: {}", orderId);
    }
}
